// pages/create-enterprise/create-enterprise.ts
import { PAGE_PUBLISH_SELECT, PAGE_MY_ENTERPRISE, goToPage } from '../../../config/pages';
import { createEnterprise, joinEnterprise } from '../../../api/enterprise.js';
import { uploadLicense, uploadEnterpriseLogo, uploadCert, uploadAgent, formatUploadResult } from '../../../api/enterprise.js';
import userManager from '../../../utils/userManager.js';
import { enterpriseCategories, getLevel1Categories } from '../../../config/enterprise-categories';

interface OptionItem {
  name: string;
  value: string;
}

interface FormData {
  company_name: string;
  company_type: string;
  funding_stage: string;
  staff_size: string;
  company_nature: string;
  contact_name: string;
  contact_phone: string;
  company_address: string;
  company_description: string;
}

interface CategoryItem {
  path: string;
  level1: string;
  level2: string;
  level3: string;
}

interface EnterpriseCategories {
  [key: string]: {
    [key: string]: string[];
  };
}

Page({
  data: {
    // 表单数据
    formData: {
      company_name: '',
      company_type: '',
      funding_stage: '',
      staff_size: '',
      company_nature: '',
      contact_name: '',
      contact_phone: '',
      company_address: '',
      company_description: ''
    } as FormData,
    
    // 企业类别三层数据结构（从配置文件导入）
    enterpriseCategories: enterpriseCategories as EnterpriseCategories,
    
    // 企业类别选择状态
    selectedCategories: [] as CategoryItem[],
    showCategoryModal: false,
    currentSelection: {
      level1: '',
      level2: '',
      level3: ''
    },
    level1List: [] as string[],
    level2List: [] as string[],
    level3List: [] as string[],
    selectedLevel1: '',
    selectedLevel2: '',
    selectedLevel3: '',
    
    // 新的分类选择状态（参考edit-company）
    currentCategoryLevel: 'level1', // level1, level2, level3
    currentCategoryList: [] as string[],
    tempSelectedLevel1: '',
    tempSelectedLevel2: '',
    tempSelectedLevel3: '',
    
    fundingStageList: [
      { name: '请选择融资阶段', value: '' },
      { name: '种子轮', value: 'seed' },
      { name: '天使轮', value: 'angel' },
      { name: 'A轮', value: 'a' },
      { name: 'B轮', value: 'b' },
      { name: 'C轮', value: 'c' },
      { name: 'D轮及以上', value: 'd' },
      { name: '已上市', value: 'ipo' },
      { name: '未融资', value: 'none' }
    ] as OptionItem[],
    fundingStageIndex: 0,
    
    staffSizeList: [
      { name: '请选择人员规模', value: '' },
      { name: '1-10人', value: '1-10' },
      { name: '11-50人', value: '11-50' },
      { name: '51-200人', value: '51-200' },
      { name: '201-500人', value: '201-500' },
      { name: '501-1000人', value: '501-1000' },
      { name: '1000人以上', value: '1000+' }
    ] as OptionItem[],
    staffSizeIndex: 0,
    
    companyNatureList: [
      { name: '请选择公司性质', value: '' },
      { name: '有限责任公司', value: 'limited' },
      { name: '股份有限公司', value: 'joint' },
      { name: '合伙企业', value: 'partnership' },
      { name: '个人独资企业', value: 'individual' },
      { name: '外商投资企业', value: 'foreign' },
      { name: '其他', value: 'other' }
    ] as OptionItem[],
    companyNatureIndex: 0,
    
    // 文件上传
    logoFiles: [] as any[],
    licenseFile: null as any,
    certFile: null as any,
    agentFile: null as any,
    
    // 会员弹框
    showMembershipModal: false,
    
    // 加入企业弹窗
    showJoinEnterpriseModal: false,
    joinEnterpriseName: ''
  },

  onLoad() {
    console.log('创建企业页面加载完成');
    this.initializeCategories();
  },
  
  // 初始化分类列表
  initializeCategories() {
    const level1List = getLevel1Categories();
    this.setData({
      level1List,
      currentCategoryLevel: 'level1'
    }, () => {
      // 初始化完成后加载一级分类列表
      this.loadCategoryList();
    });
  },

  onShow() {
    console.log('创建企业页面显示');
  },

  // 点击页面其他地方关闭弹窗
  onPageTap(e: any) {
    // 这里可以添加关闭弹窗的逻辑
  },

  // 企业全称输入
  onCompanyNameInput(e: any) {
    this.setData({
      'formData.company_name': e.detail.value
    });
  },

  // 联系人输入
  onContactNameInput(e: any) {
    this.setData({
      'formData.contact_name': e.detail.value
    });
  },

  // 联系电话输入
  onContactPhoneInput(e: any) {
    this.setData({
      'formData.contact_phone': e.detail.value
    });
  },

  // 公司地址输入
  onCompanyAddressInput(e: any) {
    this.setData({
      'formData.company_address': e.detail.value
    });
  },

  // 公司描述输入
  onCompanyDescriptionInput(e: any) {
    this.setData({
      'formData.company_description': e.detail.value
    });
  },

  // 显示分类选择器
  showCategorySelector() {
    if (this.data.selectedCategories.length >= 5) {
      wx.showToast({
        title: '最多只能选择5个企业类别',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      showCategoryModal: true,
      currentCategoryLevel: 'level1',
      currentCategoryList: this.data.level1List,
      tempSelectedLevel1: '',
      tempSelectedLevel2: '',
      tempSelectedLevel3: ''
    });
  },

  // 隐藏分类选择器
  hideCategorySelector() {
    this.setData({
      showCategoryModal: false
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 切换分类级别
  switchCategoryLevel(e: any) {
    const level = e.currentTarget.dataset.level;
    this.setData({
      currentCategoryLevel: level
    });
    this.loadCategoryList();
  },

  // 加载分类列表
  loadCategoryList() {
    const { currentCategoryLevel, tempSelectedLevel1, tempSelectedLevel2, enterpriseCategories } = this.data;
    let categoryList: string[] = [];

    if (currentCategoryLevel === 'level1') {
      // 一级：主要类别
      categoryList = this.data.level1List;
    } else if (currentCategoryLevel === 'level2' && tempSelectedLevel1) {
      // 二级：子类别
      categoryList = Object.keys(enterpriseCategories[tempSelectedLevel1] || {});
    } else if (currentCategoryLevel === 'level3' && tempSelectedLevel1 && tempSelectedLevel2) {
      // 三级：具体类别
      categoryList = enterpriseCategories[tempSelectedLevel1]?.[tempSelectedLevel2] || [];
    }

    this.setData({
      currentCategoryList: categoryList
    });
  },

  // 从分类弹窗中选择主要类别
  selectLevel1FromCategory(e: any) {
    const level1 = e.currentTarget.dataset.category;
    
    this.setData({
      tempSelectedLevel1: level1,
      tempSelectedLevel2: '',
      tempSelectedLevel3: '',
      currentCategoryLevel: 'level2'
    }, () => {
      // 在数据更新后加载二级分类列表
      this.loadCategoryList();
    });
  },

  // 从分类弹窗中选择子类别
  selectLevel2FromCategory(e: any) {
    const level2 = e.currentTarget.dataset.category;
    
    this.setData({
      tempSelectedLevel2: level2,
      tempSelectedLevel3: ''
    }, () => {
      // 检查是否有三级分类，如果有则切换到三级，否则直接确认选择
      const { tempSelectedLevel1, enterpriseCategories } = this.data;
      const level3List = enterpriseCategories[tempSelectedLevel1]?.[level2] || [];
      
      if (level3List.length > 0) {
        this.setData({
          currentCategoryLevel: 'level3'
        }, () => {
          this.loadCategoryList();
        });
      } else {
        // 如果没有三级分类，直接确认选择
        this.confirmCategorySelection();
      }
    });
  },

  // 从分类弹窗中选择具体类别
  selectLevel3FromCategory(e: any) {
    const level3 = e.currentTarget.dataset.category;
    
    this.setData({
      tempSelectedLevel3: level3
    });
    
    // 选择三级分类后直接确认
    this.confirmCategorySelection();
  },

  // 清除分类筛选
  clearCategoryFilter() {
    this.setData({
      tempSelectedLevel1: '',
      tempSelectedLevel2: '',
      tempSelectedLevel3: '',
      currentCategoryLevel: 'level1'
    });
    this.loadCategoryList();
  },

  // 选择第一级分类
  selectLevel1(e: any) {
    const level1 = e.currentTarget.dataset.category;
    const level2List = Object.keys(this.data.enterpriseCategories[level1] || {});
    
    this.setData({
      selectedLevel1: level1,
      selectedLevel2: '',
      selectedLevel3: '',
      'currentSelection.level1': level1,
      'currentSelection.level2': '',
      'currentSelection.level3': '',
      level2List,
      level3List: []
    });
  },

  // 选择第二级分类
  selectLevel2(e: any) {
    const level2 = e.currentTarget.dataset.category;
    const { selectedLevel1, enterpriseCategories } = this.data;
    const level3List = enterpriseCategories[selectedLevel1]?.[level2] || [];
    
    this.setData({
      selectedLevel2: level2,
      selectedLevel3: '',
      'currentSelection.level2': level2,
      'currentSelection.level3': '',
      level3List
    });
  },

  // 选择第三级分类
  selectLevel3(e: any) {
    const level3 = e.currentTarget.dataset.category;
    
    this.setData({
      selectedLevel3: level3,
      'currentSelection.level3': level3
    });
  },

  // 确认分类选择
  confirmCategorySelection() {
    const { tempSelectedLevel1, tempSelectedLevel2, tempSelectedLevel3, selectedCategories } = this.data;
    
    if (!tempSelectedLevel1) {
      wx.showToast({
        title: '请选择类别',
        icon: 'none'
      });
      return;
    }
    
    let categoryPath = tempSelectedLevel1;
    if (tempSelectedLevel2) {
      categoryPath += ` > ${tempSelectedLevel2}`;
      if (tempSelectedLevel3) {
        categoryPath += ` > ${tempSelectedLevel3}`;
      }
    }
    
    if (selectedCategories.some(cat => cat.path === categoryPath)) {
      wx.showToast({
        title: '该类别已选择',
        icon: 'none'
      });
      return;
    }
    
    const newCategories = [...selectedCategories, {
      path: categoryPath,
      level1: tempSelectedLevel1,
      level2: tempSelectedLevel2,
      level3: tempSelectedLevel3
    }];
    
    const categoryTypes = newCategories.map(cat => cat.level3 || cat.level2 || cat.level1);
    
    this.setData({
      selectedCategories: newCategories,
      'formData.company_type': categoryTypes.join(',')
    });
    
    this.hideCategorySelector();
  },

  // 删除选择的分类
  removeCategory(e: any) {
    const index = e.currentTarget.dataset.index;
    const { selectedCategories } = this.data;
    const newCategories = selectedCategories.filter((_, i) => i !== index);
    
    // 更新表单数据
    const categoryTypes = newCategories.map(cat => cat.level3 || cat.level2 || cat.level1);
    
    this.setData({
      selectedCategories: newCategories,
      'formData.company_type': categoryTypes.join(',')
    });
  },

  // 融资阶段变化
  onFundingStageChange(e: any) {
    const index = e.detail.value;
    const item = this.data.fundingStageList[index];
    this.setData({
      fundingStageIndex: index,
      'formData.funding_stage': item.value
    });
  },

  // 人员规模变化
  onStaffSizeChange(e: any) {
    const index = e.detail.value;
    const item = this.data.staffSizeList[index];
    this.setData({
      staffSizeIndex: index,
      'formData.staff_size': item.value
    });
  },

  // 公司性质变化
  onCompanyNatureChange(e: any) {
    const index = e.detail.value;
    const item = this.data.companyNatureList[index];
    this.setData({
      companyNatureIndex: index,
      'formData.company_nature': item.value
    });
  },

  // Logo上传成功回调
  onLogoUploadSuccess(e: any) {
    const { allImages } = e.detail;
    console.log('Logo上传成功，完整数据:', allImages);
    
    // 保存完整的 Logo 数据对象，为企业提交做准备
    this.setData({
      logoFiles: allImages.map((img: any) => ({
        url: img.url,
        path: img.url,
        name: img.name || 'logo',
        size: img.size
      }))
    });
  },

  // Logo删除回调
  onLogoRemove(e: any) {
    const { remainingImages } = e.detail;
    console.log('删除Logo后剩余数据:', remainingImages);
    
    // 更新 Logo 数据
    this.setData({
      logoFiles: remainingImages.map((img: any) => ({
        url: img.url,
        path: img.url,
        name: img.name || 'logo',
        size: img.size
      }))
    });
  },

  // 上传营业执照
  async uploadLicense() {
    try {
      const res = await wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      }) as any;
      
      const filePath = res.tempFilePaths[0];
      
      wx.showLoading({ title: '上传中...' });
      
      const uploadResult = await uploadLicense(filePath);
      
      wx.hideLoading();
      
      if (uploadResult.code === 200 && uploadResult.data) {
        this.setData({
          licenseFile: {
            path: filePath,
            url: uploadResult.data.url,
            name: uploadResult.data.name || '营业执照'
          }
        });
        wx.showToast({
          title: '营业执照上传成功',
          icon: 'success'
        });
      } else {
        throw new Error(uploadResult.msg || '上传失败');
      }
    } catch (error: any) {
      console.error('上传营业执照失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '上传失败'),
        icon: 'none'
      });
    }
  },

  // 上传认证体系文件
  async uploadCert() {
    try {
      const res = await wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      }) as any;
      
      const filePath = res.tempFilePaths[0];
      
      wx.showLoading({ title: '上传中...' });
      
      const uploadResult = await uploadCert(filePath);
      
      wx.hideLoading();
      
      if (uploadResult.code === 200 && uploadResult.data) {
        this.setData({
          certFile: {
            path: filePath,
            url: uploadResult.data.url,
            name: uploadResult.data.name || '认证体系文件'
          }
        });
        wx.showToast({
          title: '认证体系文件上传成功',
          icon: 'success'
        });
      } else {
        throw new Error(uploadResult.msg || '上传失败');
      }
    } catch (error: any) {
      console.error('上传认证体系文件失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '上传失败'),
        icon: 'none'
      });
    }
  },
  
  // 上传代理证书
  async uploadAgent() {
    try {
      const res = await wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      }) as any;
      
      const filePath = res.tempFilePaths[0];
      
      wx.showLoading({ title: '上传中...' });
      
      const uploadResult = await uploadAgent(filePath);
      
      wx.hideLoading();
      
      if (uploadResult.code === 200 && uploadResult.data) {
        this.setData({
          agentFile: {
            path: filePath,
            url: uploadResult.data.url,
            name: uploadResult.data.name || '代理证书'
          }
        });
        wx.showToast({
          title: '代理证书上传成功',
          icon: 'success'
        });
      } else {
        throw new Error(uploadResult.msg || '上传失败');
      }
    } catch (error: any) {
      console.error('上传代理证书失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '上传失败'),
        icon: 'none'
      });
    }
  },

  // 更新上传区域显示
  updateUploadArea(type: string, uploaded: boolean, fileName: string) {
    // 这里可以根据需要更新UI显示
    console.log(`更新${type}上传区域:`, uploaded, fileName);
  },

  // 删除文件
  removeFile(type: string) {
    if (type === 'license') {
      this.setData({
        licenseFile: null
      });
    } else if (type === 'cert') {
      this.setData({
        certFile: null
      });
    } else if (type === 'agent') {
      this.setData({
        agentFile: null
      });
    }
  },

  // 提交表单
  async submitForm() {
    // 表单验证
    if (!this.validateForm()) {
      return;
    }
    
    // 验证营业执照
    // if (!this.data.licenseFile) {
    //   wx.showToast({
    //     title: '请上传营业执照',
    //     icon: 'none'
    //   });
    //   return;
    // }
    
    wx.showLoading({ title: '提交中...' });
    
    try {
      // 准备提交数据
      const submitData: any = {
        name: this.data.formData.company_name,
        contact_name: this.data.formData.contact_name,
        contact_phone: this.data.formData.contact_phone,
        tags: this.data.formData.company_type,
        funding_stage: this.data.formData.funding_stage,
        staff_size: this.data.formData.staff_size,
        nature: this.data.formData.company_nature,
        address: this.data.formData.company_address,
        description: this.data.formData.company_description
      };
      
      // 添加营业执照（必填）
      if (this.data.licenseFile && this.data.licenseFile.url) {
        submitData.license_file = JSON.stringify([this.data.licenseFile.url]);
      }
      
      // 添加Logo文件（使用完整的图片数据）
      if (this.data.logoFiles.length > 0) {
        submitData.logo_files = JSON.stringify(
          this.data.logoFiles.map(file => ({
            url: file.url,
            name: file.name || 'logo',
            size: file.size,
            path: file.path
          })).filter(file => file.url)
        );
      }
      
      // 添加ISO认证文件（可选）
      if (this.data.certFile && this.data.certFile.url) {
        submitData.cert_file = JSON.stringify([this.data.certFile.url]);
      }
      
      // 添加其他资质文件（可选）
      if (this.data.agentFile && this.data.agentFile.url) {
        submitData.agent_file = JSON.stringify([this.data.agentFile.url]);
      }
      
      // 调用创建企业API
      const result = await createEnterprise(submitData);
      
      wx.hideLoading();
      
      if (result.status === 200) {
        // ✅ 企业创建成功，刷新用户信息缓存（包含企业数据）
        await userManager.refreshAfterUpdate('企业创建');
        console.log('企业创建成功',result);

        setTimeout(() => {
          console.log('跳转到我的企业详情页面',PAGE_MY_ENTERPRISE);
          // 跳转到我的企业详情页面
          goToPage(PAGE_MY_ENTERPRISE, {}, 'redirectTo');
        }, 2000);

        wx.showToast({
          title: '企业创建成功，等待审核',
          icon: 'success',
          duration: 2000
        });
        

      } else {
        wx.showToast({
          title: result.msg || '创建失败',
          icon: 'none'
        });
      }
    } catch (error: any) {
      console.error('创建企业失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '创建失败，请重试'),
        icon: 'none'
      });
    }
  },

  // 表单验证（简化验证：只验证必填项）
  validateForm(): boolean {
    const { formData } = this.data;
    
    // 验证企业全称
    if (!formData.company_name.trim()) {
      wx.showToast({
        title: '请输入企业全称',
        icon: 'none'
      });
      return false;
    }
    
    // 验证企业类别
    if (!formData.company_type.trim()) {
      wx.showToast({
        title: '请选择企业类别',
        icon: 'none'
      });
      return false;
    }
    
    // 验证融资阶段
    if (!formData.funding_stage.trim()) {
      wx.showToast({
        title: '请选择融资阶段',
        icon: 'none'
      });
      return false;
    }
    
    // 验证人员规模
    if (!formData.staff_size.trim()) {
      wx.showToast({
        title: '请选择人员规模',
        icon: 'none'
      });
      return false;
    }
    
    // 验证公司性质
    if (!formData.company_nature.trim()) {
      wx.showToast({
        title: '请选择公司性质',
        icon: 'none'
      });
      return false;
    }
    
    // 验证联系人
    if (!formData.contact_name.trim()) {
      wx.showToast({
        title: '请输入联系人姓名',
        icon: 'none'
      });
      return false;
    }
    
    // 验证联系电话
    if (!formData.contact_phone.trim()) {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none'
      });
      return false;
    }
    
    // 验证联系电话格式（手机号或固定电话）
    const phonePattern = /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/;
    if (!phonePattern.test(formData.contact_phone.trim())) {
      wx.showToast({
        title: '请输入有效的手机号码或固定电话',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    
    return true;
  },
  
  // 显示加入企业弹窗
  showJoinEnterpriseModal() {
    this.setData({
      showJoinEnterpriseModal: true,
      joinEnterpriseName: ''
    });
  },
  
  // 关闭加入企业弹窗
  closeJoinEnterpriseModal() {
    this.setData({
      showJoinEnterpriseModal: false,
      joinEnterpriseName: ''
    });
  },
  
  // 输入加入企业名称
  onJoinEnterpriseNameInput(e: any) {
    this.setData({
      joinEnterpriseName: e.detail.value
    });
  },
  
  // 确认加入企业
  async confirmJoinEnterprise() {
    const { joinEnterpriseName } = this.data;
    
    if (!joinEnterpriseName.trim()) {
      wx.showToast({
        title: '请输入企业全称',
        icon: 'none'
      });
      return;
    }
    
    if (joinEnterpriseName.trim().length < 1) {
      wx.showToast({
        title: '企业名称不能为空',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({
      title: '加入中...'
    });
    
    try {
      // 尝试将输入解析为企业ID（数字）或企业名称
      const enterpriseId = joinEnterpriseName.trim();
      
      if ((enterpriseId.length<0)) {
        // 如果不是数字，提示输入企业ID
        wx.hideLoading();
        wx.showToast({
          title: '请输入企业全称',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      // 调用加入企业API
      const result = await joinEnterprise(enterpriseId);
      
      wx.hideLoading();
      
      if (result.code === 200) {
        // ✅ 加入企业成功，刷新用户信息缓存（包含企业数据）
        await userManager.refreshAfterUpdate('加入企业');
        
        wx.showToast({
          title: '成功加入企业',
          icon: 'success',
          duration: 2000
        });
        
        this.closeJoinEnterpriseModal();
        
        // 延迟跳转
        setTimeout(() => {
          // 跳转到我的企业详情页面
          goToPage(PAGE_MY_ENTERPRISE, {}, 'redirectTo');
        }, 2000);
      } else {
        wx.showToast({
          title: result.msg || '加入失败',
          icon: 'none'
        });
      }
    } catch (error: any) {
      console.error('加入企业失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '加入失败，请重试'),
        icon: 'none'
      });
    }
  },

  // 显示会员开通弹框
  showMembershipModal() {
    this.setData({
      showMembershipModal: true
    });
  },

  // 关闭会员开通弹框
  closeMembershipModal() {
    this.setData({
      showMembershipModal: false
    });
  },

  // 开通会员
  openMembership() {
    console.log('开通会员');
    
    // 显示加载中
    wx.showLoading({
      title: '开通中...'
    });
    
    // 模拟开通请求
    setTimeout(() => {
      wx.hideLoading();
      
      // 关闭弹框
      this.closeMembershipModal();
      
      // 显示开通成功
      wx.showToast({
        title: '会员开通成功',
        icon: 'success'
      });
      
      // 跳转到发布选择页
      setTimeout(() => {
        goToPage(PAGE_PUBLISH_SELECT);
      }, 1500);
    }, 2000);
  },

  // 显示帮助
  showHelp() {
    wx.showModal({
      title: '企业认证帮助',
      content: '请按照要求填写企业信息并上传相关资质文件，我们将在1-3个工作日内完成审核。',
      showCancel: false,
      confirmText: '我知道了'
    });
  }
});
